package cn.tedu.charging.order.config;

import cn.tedu.charging.order.mqtt.MqttConsumer;
import cn.tedu.charging.order.mqtt.MqttContext;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Random;

/**
 * EMQX消息中间件 的连接配置
 */
@Configuration
public class MqttConfiguration {

    private static final Logger log = LoggerFactory.getLogger(MqttConfiguration.class);

    @Autowired
    MqttContext mqttContext;

    /**
     * 用户名
     * 这些配置信息 应该放到配置文件, 或者放到配置中心 nacos (注册中心和配置中心)
     */
    private String userName = "admin";

    /**
     * 密码
     */
    private String password = "public";

    /**
     * 连接地址 tcp协议 端口 1883
     * mysql jdbc://localhost:3306/databaseName
     */
    private String host = "tcp://localhost:1883";

    /**
     * 客户端 启动多个订单服务,需要保证每个订单服务的clientId 不同
     */
    private String clientId = "order_service_client" + getRandom();

    private Integer getRandom(){
        Random random = new Random();
        return random.nextInt(100);
    }

    @Bean
    public MqttClient mqttClient() throws MqttException {

        MqttClient mqttClient = new MqttClient(host,clientId);


        MqttConnectOptions options = new MqttConnectOptions();


        options.setUserName(userName);

        options.setPassword(password.toCharArray());

        //清理会话
        options.setCleanSession(true);

        //是否重置
        options.setAutomaticReconnect(true);

        //版本号设置
        options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
        MqttConsumer mqttConsumer = new MqttConsumer(mqttClient ,mqttContext);
        mqttClient.setCallback(mqttConsumer);

        mqttClient.connect(options);


        return mqttClient;
    }

}
